package http;

import java.util.HashMap;


import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

import common.AbsTask;
import common.PreferUtil;


/**
 * Depiction: 异步登录，包含处理首次注册昵称修改功能
 * <p>
 * Modify:
 * <p>
 * Author: Kevin Lynn
 * <p>
 * Create Date：2016年2月2日 下午12:57:34
 * <p>
 *
 * @version 1.0
 * @since 1.0
 */
public abstract class LoginTask extends AbsTask {
    private String gender;
    private String nickname;
    private String openid;
    private String portrait;
    private String unionid;
    private String userType;

    /**
     * @param gender   性别
     * @param nickname 昵称
     * @param openid   mob产生的UserToken
     * @param portrait 头像
     */
    public LoginTask(String userType, String gender, String nickname, String openid, String portrait, String unionid) {
        this.userType = userType;
        this.gender = gender;
        this.nickname = nickname;
        this.openid = openid;
        this.portrait = portrait;
        this.unionid = unionid;

    }

    public void excute() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("userType", userType);
        params.put("gender", gender);
        params.put("nickname", nickname);
        params.put("openid", openid);
        params.put("portrait", portrait);
        if (unionid != null) {
            params.put("unionid", unionid);
        }
        Log.e(this.getClass().getSimpleName(), "onPostExecute params"+params);
        HttpAsyncTask http = new HttpAsyncTask() {
            @Override
            public void onStart(String taskId) {
                Log.e(this.getClass().getSimpleName(), "onStart()");
            }

            @Override
            public void onFinish(String taskId, String response) {
                Log.e(this.getClass().getSimpleName(), "onFinish()==>" + response);
                JsonMap data = JsonMap.parseJson(response.replaceAll("&mdash;", "——"));
                if (data == null) {
                    onPreExecute();
                    return;
                }
                if (data.getInt("code") == 200) {
                    LoginModel model = new Gson().fromJson(data.getMap("data").toString(), LoginModel.class);
                    PreferUtil.saveUserId(String.valueOf(model.getId()));
                    onPostExecute(true, model);
                } else {
                    onPreExecute();
                }
            }
        };
        http.setDebug(true);
        http.excute(Url.BaseUrl + "/user/login", params, "POST");
    }
}
